import logging
from datetime import datetime
from typing import List, Dict
from demo.models.schemas import DeviceStatus

logger = logging.getLogger(__name__)


class DeviceService:
    def __init__(self):
        self.registered_devices: Dict[str, DeviceStatus] = {}

    async def register_device(self, device_status: DeviceStatus) -> bool:
        """注册设备"""
        try:
            device_status.lastSeen = datetime.now()
            self.registered_devices[device_status.deviceId] = device_status
            logger.info(f"设备注册成功: {device_status.deviceId}")
            return True
        except Exception as e:
            logger.error(f"设备注册失败: {str(e)}")
            return False

    async def update_device_status(self, device_id: str, status: str = "active"):
        """更新设备状态"""
        if device_id in self.registered_devices:
            self.registered_devices[device_id].status = status
            self.registered_devices[device_id].lastSeen = datetime.now()
            logger.info(f"更新设备状态: {device_id} -> {status}")

    async def get_device(self, device_id: str) -> DeviceStatus:
        """获取设备信息"""
        return self.registered_devices.get(device_id)

    async def list_devices(self) -> List[DeviceStatus]:
        """获取所有设备列表"""
        return list(self.registered_devices.values())

    async def process_data_points(self, device_id: str, data_points: List[Dict]):
        """处理数据点"""
        if not data_points:
            return

        logger.info(f"处理设备 {device_id} 的数据点:")
        for i, point in enumerate(data_points):
            logger.info(f"数据点 {i + 1}: {point}")
            # 这里可以添加具体的数据处理逻辑
            # 例如：存储到数据库、进行分析、触发告警等